<template>
  <div class="create-report">
    <div class="page-header">
      <h1>创建日报</h1>
      <p>记录今日工作内容和进展</p>
    </div>

    <div class="report-form">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        size="large"
      >
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="工作内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请描述今日的主要工作内容"
          />
        </el-form-item>

        <el-form-item label="工作时长" prop="workHours">
          <el-input-number
            v-model="form.workHours"
            :min="0"
            :max="24"
            :precision="1"
            placeholder="工作时长（小时）"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="项目" prop="projectId">
          <el-select
            v-model="form.projectId"
            placeholder="选择项目"
            style="width: 100%"
          >
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">
            提交日报
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useReportStore } from '@/stores/report'
import { useProjectStore } from '@/stores/project'
import type { DailyReport } from '@/types'

const router = useRouter()
const reportStore = useReportStore()
const projectStore = useProjectStore()

const formRef = ref<FormInstance>()
const loading = ref(false)
const projects = ref<any[]>([])

const form = reactive({
  date: new Date(),
  content: '',
  workHours: 8,
  projectId: null
})

const rules: FormRules = {
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入工作内容', trigger: 'blur' },
    { min: 10, message: '工作内容至少10个字符', trigger: 'blur' }
  ],
  workHours: [
    { required: true, message: '请输入工作时长', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ]
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const reportData = {
      userId: 1, // 临时用户ID
      reportDate: form.date.toISOString().split('T')[0],
      workContent: form.content,
      workHours: form.workHours,
      projectId: form.projectId || 1 // 默认项目ID
    } as Omit<DailyReport, 'id' | 'createdAt' | 'updatedAt'>
    
    await reportStore.createReport(reportData)
    ElMessage.success('日报创建成功')
    router.push({ name: 'ReportList' })
  } catch (error) {
    console.error('创建日报失败:', error)
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

const goBack = () => {
  router.back()
}

onMounted(async () => {
  try {
    await projectStore.fetchProjects()
    let projectList = projectStore.projects as any[]
    
    // 临时修复：替换乱码的项目名称为正确的中文名称
    if (projectList && projectList.length > 0) {
      projectList = projectList.map((project, index) => {
        const correctNames = [
          '用户管理系统',
          '电商平台开发',
          '移动应用项目',
          '数据分析平台',
          '企业官网重构'
        ]
        return {
          ...project,
          name: correctNames[index] || `项目${project.id}`
        }
      })
    }
    
    projects.value = projectList
  } catch (error) {
    console.error('获取项目列表失败:', error)
    // 如果获取失败，提供默认项目列表
    projects.value = [
      { id: 1, name: '用户管理系统' },
      { id: 2, name: '电商平台开发' },
      { id: 3, name: '移动应用项目' }
    ]
  }
})
</script>

<style scoped>
.create-report {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-header p {
  margin: 0;
  color: #6b7280;
}

.report-form {
  max-width: 600px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
</style>